import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:file_selector/file_selector.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:charset/charset.dart';
import 'package:provider/provider.dart';
import '../core/sites.dart';
import '../core/theme_config.dart';

class SetPage extends StatefulWidget {
  const SetPage({Key? key}) : super(key: key);

  @override
  State<SetPage> createState() => _SetPageState();
}

class _SetPageState extends State<SetPage> {
  List<VideoSite> _sites = [];
  List<VideoSite> _builtInSites = [];
  List<VideoSite> _customSites = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadSites();
  }

  Future<void> _loadSites() async {
    setState(() => _isLoading = true);
    _sites = await SitesRepository.loadSites();
    final separated = await SitesRepository.separateSites(_sites);
    _builtInSites = separated['builtIn']!;
    _customSites = separated['custom']!;
    setState(() => _isLoading = false);
  }

  Future<void> _importSitesFromJson() async {
    try {
      final XFile? file = await openFile(
        acceptedTypeGroups: [XTypeGroup(extensions: ['json'])]
      );

      if (file != null) {
        print('选择的文件: ${file.name}');
        
        // 读取文件内容
        final fileBytes = await file.readAsBytes();
        if (fileBytes.isEmpty) {
          print('文件字节为空');
          throw FormatException('JSON文件内容为空');
        }
        
        // 尝试UTF-8解码
        String fileContent;
        try {
          fileContent = utf8.decode(fileBytes);
        } catch (e) {
          // 如果UTF-8失败，尝试GBK编码（常见中文编码）
          try {
            fileContent = gbk.decode(fileBytes);
          } catch (e) {
            // 如果GBK失败，尝试其他中文编码
            try {
              fileContent = utf16.decode(fileBytes);
            } catch (e) {
              // 如果都失败，使用系统默认编码
              fileContent = String.fromCharCodes(fileBytes);
            }
          }
        }
        // 验证JSON格式
        final parsed = jsonDecode(fileContent);
        
        if (parsed is! Map<String, dynamic>) {
          throw FormatException('JSON格式不正确，应为Map类型');
        }
        
        if (!parsed.containsKey('api_site')) {
          throw FormatException('无效的站点JSON格式，缺少api_site字段');
        }

        await SitesRepository.importSitesJson(fileContent);
        await _loadSites();
        
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('成功导入 ${_sites.length} 个站点')),
          );
        }
      }
    } on FormatException catch (e) {
      print('FormatException: ${e.message}');
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: ${e.message}')),
        );
      }
    } catch (e) {
      print('Exception: $e');
      print('Stack trace: ${e is Error ? e.stackTrace : ''}');
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('导入失败: $e')),
        );
      }
    }
  }

  Future<void> _deleteSite(VideoSite site) async {
    final prefs = await SharedPreferences.getInstance();
    final customJson = prefs.getString(SitesRepository.prefsKey);
    
    if (customJson != null) {
      final Map<String, dynamic> data = jsonDecode(customJson);
      final Map<String, dynamic> apiSite = Map.from(data['api_site'] ?? {});
      
      apiSite.remove(site.id);
      data['api_site'] = apiSite;
      
      await prefs.setString(SitesRepository.prefsKey, jsonEncode(data));
      await _loadSites();
      
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已删除站点: ${site.name}')),
        );
      }
    }
  }

  Future<void> _deleteAllSites() async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除所有自定义站点吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text('删除', style: TextStyle(color: Colors.red)),
          )
        ],
      ),
    );

    if (result == true) {
      setState(() {
        _isLoading = true;
      });

      try {
        await SitesRepository.deleteAllSites();
        await _loadSites();
        
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已删除所有自定义站点')),
          );
        }
      } catch (e) {
        print('删除所有站点失败: $e');
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除失败: $e')),
          );
        }
      } finally {
        if (context.mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  Future<void> _addSite() async {
    final TextEditingController idController = TextEditingController();
    final TextEditingController nameController = TextEditingController();
    final TextEditingController apiController = TextEditingController();
    final TextEditingController detailController = TextEditingController();
    
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) {

          
          return AlertDialog(
            title: Text('添加新站点'),
            content: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: nameController,
                    decoration: InputDecoration(labelText: '站点名称 例：超级影视'),
                  ),
                  TextField(
                    controller: idController,
                    decoration: InputDecoration(labelText: '站点ID 例:cjys'),
                  ),
                  TextField(
                    controller: apiController,
                    decoration: InputDecoration(labelText: 'API地址 例：https://api.com'),
                  ),
                  TextField(
                    controller: detailController,
                    decoration: InputDecoration(labelText: '详情页地址 例：https://www.cjys.com/video'),
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: Text('添加'),
              ),
            ],
          );
        },
      ),
    );

    if (result == true) {
      final prefs = await SharedPreferences.getInstance();
      final customJson = prefs.getString(SitesRepository.prefsKey);
      final Map<String, dynamic> data = customJson != null 
          ? jsonDecode(customJson) 
          : {'api_site': {}};
      
      final Map<String, dynamic> apiSite = Map.from(data['api_site'] ?? {});
      apiSite[idController.text] = {
        'name': nameController.text,
        'api': apiController.text,
        'detail': detailController.text,
        'is_adult': false,
      };
      
      data['api_site'] = apiSite;
      await prefs.setString(SitesRepository.prefsKey, jsonEncode(data));
      // 更新缓存时间戳，确保loadSites会使用自定义配置
      final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      await prefs.setInt(SitesRepository.prefsTimeKey, now);
      await _loadSites();
      
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('成功添加站点')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeConfig = Provider.of<ThemeConfig>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text('设置'),
        toolbarHeight: 32,
        centerTitle:  false,
        automaticallyImplyLeading: false,
        backgroundColor: themeConfig.currentGradient.colors.first,
        //字体颜色
        titleTextStyle: TextStyle(fontSize: 18,color: themeConfig.currentTextColor),
        actions: [
          IconButton(
            icon: Icon(Icons.delete_forever),
            onPressed: _deleteAllSites,
            tooltip: '删除所有站点',
          ),
          IconButton(
            icon: Icon(Icons.add),
            onPressed: _addSite,
            tooltip: '添加站点',
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: themeConfig.currentGradient,
        ),
        child: _isLoading
            ? Center(child: CircularProgressIndicator())
            : Column(
                children: [
                // 主题切换
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(bottom: 8),
                        child: Text(
                          '主题设置',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.purple[700],
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 100,
                        child: ListView(
                          scrollDirection: Axis.horizontal,
                          children: ThemeConfig.themes.asMap().entries.map((entry) {
                            final index = entry.key;
                            final theme = entry.value;
                            final isSelected = Provider.of<ThemeConfig>(context).currentThemeIndex == index;
                            
                            return GestureDetector(
                                onTap: () {
                                  Provider.of<ThemeConfig>(context, listen: false).changeTheme(index);
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(content: Text('已切换到${theme['name']}')),
                                  );
                                },
                              child: Container(
                                width: 80,
                                margin: EdgeInsets.only(right: 12),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(
                                    color: isSelected ? theme['primaryColor'] : Colors.grey[300]!,
                                    width: isSelected ? 2 : 1,
                                  ),
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Container(
                                      width: 40,
                                      height: 40,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(20),
                                        gradient: theme['gradient'],
                                      ),
                                    ),
                                    SizedBox(height: 8),
                                    Text(
                                      theme['name'],
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: isSelected ? theme['primaryColor'] : Colors.black87,
                                        fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                                      ),
                                      textAlign: TextAlign.center,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ],
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                ),
                // 导入按钮
                Padding(
                  padding: EdgeInsets.all(16),
                  child: ElevatedButton.icon(
                    icon: Icon(Icons.file_upload),
                    label: Text('导入JSON站点源文件'),
                    //设置按钮颜色
                    onPressed: _importSitesFromJson,
                    style: ElevatedButton.styleFrom(
                      foregroundColor: Colors.white,  // 文字颜色
                      minimumSize: Size(double.infinity, 48),
                      backgroundColor: Colors.blue[700], // 背景颜色
                    ),
                  ),
                ),
                
                // 站点列表 - 分为内置视频源和自定义视频源
                Expanded(
                  child: ListView(
                    children: [
                      // 内置视频源菜单
                      if (_builtInSites.isNotEmpty)
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.fromLTRB(16, 16, 16, 8),
                              child: Text(
                                '内置视频源',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.blue[700],
                                ),
                              ),
                            ),
                            ..._builtInSites.map((site) => ListTile(
                              contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                              leading: Icon(Icons.language, size: 20, color: Colors.blue),
                              title: Text(
                                site.name,
                                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              subtitle: Text(
                                site.api,
                                style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              trailing: Tooltip(
                                message: '内置站点不可删除',
                                child: Icon(Icons.lock, color: Colors.grey, size: 18),
                              ),
                              onTap: () {},
                            )).toList(),
                            Divider(height: 1, thickness: 1),
                          ],
                        ),
                      
                      // 自定义视频源菜单
                      if (_customSites.isNotEmpty)
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.fromLTRB(16, 16, 16, 8),
                              child: Text(
                                '自定义视频源',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.green[700],
                                ),
                              ),
                            ),
                            ..._customSites.map((site) => ListTile(
                              contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                              leading: Icon(Icons.language, size: 20, color: Colors.green),
                              title: Text(
                                site.name,
                                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              subtitle: Text(
                                site.api,
                                style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              trailing: IconButton(
                                icon: Icon(Icons.delete, color: Colors.red, size: 18),
                                onPressed: () => _deleteSite(site),
                                tooltip: '删除站点',
                              ),
                              onTap: () {},
                            )).toList(),
                          ],
                        ),
                      
                      // 空状态提示
                      if (_builtInSites.isEmpty && _customSites.isEmpty)
                        Center(
                          child: Padding(
                            padding: EdgeInsets.all(32),
                            child: Text(
                              '暂无站点数据',
                              style: TextStyle(fontSize: 16, color: Colors.grey),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ],
            ),
          ),
    );
  }
}

                